﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace yafc.Activity
{
	class TaskQueue
	{
		private int max = 10;
		private List<Task> queue = new List<Task>();
		private bool stop = false;
		private bool stopped = false;
		private ManualResetEvent newTask = new ManualResetEvent(false);

		public int Max
		{
			get { return max; }
			set { max = value; }
		}
		public bool Stopped
		{
			get { return stopped; }
			set { stopped = value; }
		}

		public virtual void Add(Task T)
		{
			lock(queue)
			{
				if (queue.Count() < Max)
				{
					queue.Add(T);
				}
				newTask.Set();
			}
		}
		public virtual void Start()
		{
			ThreadPool.QueueUserWorkItem(Run);
		}
		public virtual void Stop()
		{
			stop = true;
		}

		protected virtual void Run(Object o)
		{
			while (!stop)
			{
				newTask.WaitOne();
				Consume();
			}
		}
		protected virtual void Consume()
		{
			Task t = null;
			lock(queue)
			{
				if (queue.Count() > 0)
				{
					t = queue.ElementAt(0);
					queue.RemoveAt(0);
				}
				if (queue.Count() == 0)
				{
					newTask.Reset();
				}
			}
			if (t != null)
			{
				t.Start();
				t.Wait();
			}
		}
	}
}
